import React from 'react';
import {
  Card,
  List,
  Input,
  Button,
  Space,
  Avatar,
  Typography,
  Tag,
  Tooltip,
  Switch,
  message,
  Divider,
} from 'antd';
import {
  RobotOutlined,
  UserOutlined,
  SendOutlined,
  ClearOutlined,
  ReloadOutlined,
  CustomerServiceOutlined,
  BulbOutlined,
} from '@ant-design/icons';

const { Text } = Typography;

// 简易 ID 生成器
const uid = () => Math.random().toString(36).slice(2);
const LS_KEY = 'helpcenter-chat-history';
// 文心一言配置（通过 .env 配置）
const BAIDU_API_KEY = import.meta.env.VITE_BAIDU_API_KEY || '';
const BAIDU_SECRET_KEY = import.meta.env.VITE_BAIDU_SECRET_KEY || '';
const WENXIN_MODEL = import.meta.env.VITE_WENXIN_MODEL || 'ernie_speed';
// 开发环境自动走 /baidu 代理；生产默认直连官方域名（也可通过环境变量覆盖）
const WENXIN_BASE_RESOLVED =
  (import.meta.env.VITE_WENXIN_BASE !== undefined && import.meta.env.VITE_WENXIN_BASE !== '')
    ? import.meta.env.VITE_WENXIN_BASE
    : (import.meta.env.DEV ? '/baidu' : 'https://aip.baidubce.com');

// 简易消息气泡组件
function Bubble({ role, content, time }) {
  const isUser = role === 'user';
  return (
    <div
      style={{
        display: 'flex',
        justifyContent: isUser ? 'flex-end' : 'flex-start',
        marginBottom: 12,
      }}
    >
      {!isUser && (
        <Avatar style={{ backgroundColor: '#1677ff' }} icon={<RobotOutlined />} />
      )}
      <div
        style={{
          maxWidth: 680,
          background: isUser ? '#E6F4FF' : '#F5F5F5',
          border: '1px solid #e8e8e8',
          borderRadius: 8,
          padding: '8px 12px',
          marginLeft: isUser ? 8 : 12,
          marginRight: isUser ? 12 : 8,
          whiteSpace: 'pre-wrap',
        }}
      >
        <div style={{ marginBottom: 4 }}>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {isUser ? '我' : '客服AI'} · {time}
          </Text>
        </div>
        <div style={{ fontSize: 14 }}>{content}</div>
      </div>
      {isUser && (
        <Avatar style={{ backgroundColor: '#87d068' }} icon={<UserOutlined />} />
      )}
    </div>
  );
}

export default function HelpCenterChat() {
  const [messages, setMessages] = React.useState(() => {
    try {
      const raw = localStorage.getItem(LS_KEY);
      if (raw) return JSON.parse(raw);
    } catch {}
    const welcome = {
      id: uid(),
      role: 'assistant',
      content: '您好，我是智能客服。请描述您的问题～',
      time: new Date().toLocaleString(),
    };
    return [welcome];
  });
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [useAI, setUseAI] = React.useState(true);

  const AI_ENDPOINT = import.meta.env.VITE_AI_CHAT_URL || '';
  const AI_API_KEY = import.meta.env.VITE_AI_API_KEY || '';
  const canUseWenxin = !!BAIDU_API_KEY && !!BAIDU_SECRET_KEY;
  const [aiAvailable, setAiAvailable] = React.useState(() => canUseWenxin || !!AI_ENDPOINT);

  React.useEffect(() => {
    try {
      localStorage.setItem(LS_KEY, JSON.stringify(messages));
    } catch {}
  }, [messages]);

  // 获取/缓存文心 access_token
  const getWenxinAccessToken = React.useCallback(async (force = false) => {
    const cached = localStorage.getItem('wenxin_access_token');
    const exp = Number(localStorage.getItem('wenxin_access_token_exp') || '0');
    if (!force && cached && Date.now() < exp) return cached;
    const url = `${WENXIN_BASE_RESOLVED}/oauth/2.0/token`;
    const form = new URLSearchParams({
      grant_type: 'client_credentials',
      client_id: BAIDU_API_KEY,
      client_secret: BAIDU_SECRET_KEY,
    });
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: form.toString(),
      mode: 'cors',
      credentials: 'omit',
    });
    if (!res.ok) {
      let reason = '';
      try {
        const errData = await res.json();
        reason = errData?.error_description || errData?.error || '';
      } catch {}
      setAiAvailable(false);
      throw new Error(`获取文心 token 失败: ${res.status}${reason ? ` - ${reason}` : ''}`);
    }
    const data = await res.json();
    if (!data.access_token) {
      setAiAvailable(false);
      throw new Error('文心响应缺少 access_token');
    }
    const expTime = Date.now() + (data.expires_in ? data.expires_in * 1000 : 25 * 24 * 3600 * 1000) - 120000; // 提前2分钟过期
    localStorage.setItem('wenxin_access_token', data.access_token);
    localStorage.setItem('wenxin_access_token_exp', String(expTime));
    setAiAvailable(true);
    return data.access_token;
  }, []);

  // 调用文心一言聊天接口
  const wenxinChat = React.useCallback(async (history) => {
    let token = await getWenxinAccessToken();
    let endpoint = `${WENXIN_BASE_RESOLVED}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${WENXIN_MODEL}?access_token=${token}`;
    const body = { messages: history.map((m) => ({ role: m.role, content: m.content })), stream: false };

    let res = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      mode: 'cors',
      credentials: 'omit',
      body: JSON.stringify(body),
    });

    // 若令牌失效（401/403），清理缓存后强制刷新令牌并重试一次
    if (res.status === 401 || res.status === 403) {
      localStorage.removeItem('wenxin_access_token');
      localStorage.removeItem('wenxin_access_token_exp');
      token = await getWenxinAccessToken(true);
      endpoint = `${WENXIN_BASE_RESOLVED}/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${WENXIN_MODEL}?access_token=${token}`;
      res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        mode: 'cors',
        credentials: 'omit',
        body: JSON.stringify(body),
      });
    }

    if (!res.ok) {
      let reason = '';
      try {
        const errData = await res.json();
        reason = errData?.error_msg || errData?.error_description || errData?.msg || '';
      } catch {}
      setAiAvailable(false);
      throw new Error(`文心接口错误: ${res.status}${reason ? ` - ${reason}` : ''}`);
    }
    const data = await res.json();
    // 文心返回通常为 { result: string }
    setAiAvailable(true);
    return data?.result || data?.content || JSON.stringify(data);
  }, [getWenxinAccessToken]);

  const sendUser = React.useCallback(
    async (text) => {
      if (!text?.trim()) return;
      const userMsg = {
        id: uid(),
        role: 'user',
        content: text.trim(),
        time: new Date().toLocaleString(),
      };
      setMessages((prev) => [...prev, userMsg]);
      setLoading(true);
      setInput('');

      try {
        let assistantReply = '';
        if (useAI) {
          const history = messages.concat(userMsg);
          if (canUseWenxin) {
            assistantReply = await wenxinChat(history);
          } else if (AI_ENDPOINT) {
            const payload = { messages: history.map((m) => ({ role: m.role, content: m.content })) };
            const res = await fetch(AI_ENDPOINT, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                ...(AI_API_KEY ? { Authorization: `Bearer ${AI_API_KEY}` } : {}),
              },
              mode: 'cors',
              credentials: 'omit',
              body: JSON.stringify(payload),
            });
            if (!res.ok) throw new Error(`AI 接口错误: ${res.status}`);
            const data = await res.json();
            assistantReply = data?.text || data?.reply || data?.choices?.[0]?.message?.content || JSON.stringify(data);
          } else {
            assistantReply = `我已收到："${userMsg.content}"\n\n建议：尝试提供设备编号、发生时间与具体现象，以便快速定位问题。`;
          }
        } else {
          // 关闭 AI 时的模拟回复
          assistantReply = `我已收到："${userMsg.content}"\n\n建议：尝试提供设备编号、发生时间与具体现象，以便快速定位问题。`;
        }

        const aiMsg = {
          id: uid(),
          role: 'assistant',
          content: assistantReply,
          time: new Date().toLocaleString(),
        };
        setMessages((prev) => [...prev, aiMsg]);
      } catch (err) {
        console.error(err);
        message.error(`发送失败：AI 接口不可用、CORS 或网络错误${err?.message ? `（${err.message}）` : ''}`);
        const aiMsg = {
          id: uid(),
          role: 'assistant',
          content:
            (canUseWenxin
              ? '抱歉，文心一言接口不可用或浏览器跨域限制。可考虑后端代理方式。'
              : '抱歉，当前 AI 接口不可用，请稍后重试或联系人工客服。'),
          time: new Date().toLocaleString(),
        };
        setMessages((prev) => [...prev, aiMsg]);
      } finally {
        setLoading(false);
      }
    },
    [messages, useAI, AI_ENDPOINT, AI_API_KEY, canUseWenxin, wenxinChat]
  );

  const onSend = () => {
    if (!navigator.onLine) {
      message.error('网络不可用，已限制发送');
      return;
    }
    if (useAI && !aiAvailable) {
      message.warning('AI不可用：请关闭 AI 开关以使用模拟应答');
      return;
    }
    sendUser(input);
  };
  const onKeyDown = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      onSend();
    }
  };

  const onClear = () => {
    const welcome = {
      id: uid(),
      role: 'assistant',
      content: '历史已清空。请继续描述您的问题～',
      time: new Date().toLocaleString(),
    };
    setMessages([welcome]);
  };

  const onRegenerate = async () => {
    if (useAI && !aiAvailable) {
      message.warning('AI不可用：请关闭 AI 开关以使用模拟应答');
      return;
    }
    const lastUser = [...messages].reverse().find((m) => m.role === 'user');
    if (!lastUser) return message.info('暂无可重试的用户问题');
    await sendUser(lastUser.content);
  };

  return (
    <Card
      title={
        <Space>
          <CustomerServiceOutlined />
          <span>客服聊天</span>
          <Tag color={useAI ? (aiAvailable ? (canUseWenxin ? 'blue' : 'green') : 'red') : 'default'}>
            {useAI
              ? (aiAvailable
                  ? (canUseWenxin ? '文心一言 · 启用' : 'AI 已启用')
                  : 'AI 不可用')
              : '模拟应答'}
          </Tag>
        </Space>
      }
      extra={
        <Space>
          <Tooltip title="切换 AI/模拟">
            <Switch checked={useAI} onChange={setUseAI} />
          </Tooltip>
          <Tooltip title="清空历史">
            <Button onClick={onClear} icon={<ClearOutlined />}>
              清空
            </Button>
          </Tooltip>
          <Tooltip title="基于上一条用户消息重新生成">
            <Button onClick={onRegenerate} icon={<ReloadOutlined />} disabled={loading}>
              重试
            </Button>
          </Tooltip>
        </Space>
      }
      variant="outlined"
    >
      <div
        style={{
          height: '52vh',
          overflowY: 'auto',
          padding: '8px 4px',
          border: '1px solid #f0f0f0',
          borderRadius: 8,
          background: '#fff',
        }}
      >
        <List
          dataSource={messages}
          renderItem={(m) => (
            <List.Item style={{ border: 'none', padding: '4px 8px' }}>
              <Bubble role={m.role} content={m.content} time={m.time} />
            </List.Item>
          )}
        />
      </div>

      <Divider style={{ margin: '12px 0' }} />

      <Space direction="vertical" style={{ width: '100%' }}>
        <Input.TextArea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={onKeyDown}
          autoSize={{ minRows: 3, maxRows: 6 }}
          placeholder={
            useAI
              ? (aiAvailable
                  ? (canUseWenxin
                      ? '文心一言：输入问题，回车发送（Shift+Enter 换行）'
                      : '输入问题，回车发送（Shift+Enter 换行）')
                  : 'AI不可用：请关闭 AI 开关以使用模拟应答')
              : '模拟应答模式：输入问题后发送'
          }
          disabled={loading || (useAI && !aiAvailable)}
        />
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <BulbOutlined />
            <Text type="secondary">
              提示：尽量包含设备编号、时间与异常信息，便于定位。
            </Text>
          </Space>
          <Button
            type="primary"
            icon={<SendOutlined />}
            loading={loading}
            onClick={onSend}
            disabled={useAI && !aiAvailable}
          >
            发送
          </Button>
        </div>
      </Space>
    </Card>
  );
}